<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>响应 JSON 数据</title>
    <style>
        .error{
            border: solid 1px #f25;
        }
    </style>
</head>
<body>
    手机号: <input type="text"><span></span>

    <script>
        //获取 input 元素
        let input = document.querySelector('input');
        let span = document.querySelector('span');
        //绑定事件
        input.onblur = function(){
            //获取用户输入的内容
            let phone = this.value;
            let xhr = new XMLHttpRequest();
            //设置响应体的格式
            // xhr.responseType = 'json';
            xhr.open('get', `http://127.0.0.1/checkPhone?phone=${phone}`);
            xhr.send();
            xhr.onload = function(){
                //1. 手动转化 JSON
                let data = JSON.parse(xhr.response);
                if(!data.available){
                    span.innerHTML = data.msg;
                    input.classList.add('error');
                }else{
                    span.innerHTML = '√';
                    input.classList.remove('error');
                }
                //2. 自动转换   需要设置 xhr.responseType = 'json'
            }
        }
    </script>
</body>
</html>